{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "# 超参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn import datasets"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 一个识别手写数字的例子"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "digits = datasets.load_digits()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_keys(['data', 'target', 'target_names', 'images', 'DESCR'])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "digits.keys()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Optical Recognition of Handwritten Digits Data Set\n===================================================\n\nNotes\n-----\nData Set Characteristics:\n    :Number of Instances: 5620\n    :Number of Attributes: 64\n    :Attribute Information: 8x8 image of integer pixels in the range 0..16.\n    :Missing Attribute Values: None\n    :Creator: E. Alpaydin (alpaydin '@' boun.edu.tr)\n    :Date: July; 1998\n\nThis is a copy of the test set of the UCI ML hand-written digits datasets\nhttp://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits\n\nThe data set contains images of hand-written digits: 10 classes where\neach class refers to a digit.\n\nPreprocessing programs made available by NIST were used to extract\nnormalized bitmaps of handwritten digits from a preprinted form. From a\ntotal of 43 people, 30 contributed to the training set and different 13\nto the test set. 32x32 bitmaps are divided into nonoverlapping blocks of\n4x4 and the number of on pixels are counted in each block. This generates\nan input matrix of 8x8 where each element is an integer in the range\n0..16. This reduces dimensionality and gives invariance to small\ndistortions.\n\nFor info on NIST preprocessing routines, see M. D. Garris, J. L. Blue, G.\nT. Candela, D. L. Dimmick, J. Geist, P. J. Grother, S. A. Janet, and C.\nL. Wilson, NIST Form-Based Handprint Recognition System, NISTIR 5469,\n1994.\n\nReferences\n----------\n  - C. Kaynak (1995) Methods of Combining Multiple Classifiers and Their\n    Applications to Handwritten Digit Recognition, MSc Thesis, Institute of\n    Graduate Studies in Science and Engineering, Bogazici University.\n  - E. Alpaydin, C. Kaynak (1998) Cascading Classifiers, Kybernetika.\n  - Ken Tang and Ponnuthurai N. Suganthan and Xi Yao and A. Kai Qin.\n    Linear dimensionalityreduction using relevance weighted LDA. School of\n    Electrical and Electronic Engineering Nanyang Technological University.\n    2005.\n  - Claudio Gentile. A New Approximate Maximal Margin Classification\n    Algorithm. NIPS. 2000.\n\n"
     ]
    }
   ],
   "source": [
    "print(digits.DESCR)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[  0.,   0.,   5., ...,   0.,   0.,   0.],\n       [  0.,   0.,   0., ...,  10.,   0.,   0.],\n       [  0.,   0.,   0., ...,  16.,   9.,   0.],\n       ..., \n       [  0.,   0.,   1., ...,   6.,   0.,   0.],\n       [  0.,   0.,   2., ...,  12.,   0.,   0.],\n       [  0.,   0.,  10., ...,  12.,   1.,   0.]])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "digits.data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1797, 64)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.shape(digits.data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "特征"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "X = digits.data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "分类"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1797,)"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y = digits.target\n",
    "np.shape(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 可视化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAPgAAAD8CAYAAABaQGkdAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDIuMS4xLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvAOZPmwAACu5JREFUeJzt3d2LXeUZhvH77qi0qTYDTVokid1BJCCFTmQTkBRjIpZYxeSgBwkoJhRypCgtiPZE+g9IelAEiU4EE6WNSkSsVtDRCq11kkxa82FJw5RM0GZCGfw4aIg+PZgViJIya7LX1zxcPwidj81+n01zudbsWVmvI0IAcvpG2wMAqA+BA4kROJAYgQOJETiQGIEDiRE4kBiBA4kROJDYFXU86ZIlS6LX69Xx1K2amZlpdL3JycnG1hoaGmpsreuvv76xtRYtWtTYWk2anJzU2bNnPdfjagm81+tpfHy8jqdu1f79+xtd77777mtsreHh4cbW2rt3b2NrjYyMNLZWk/r9fqnHcYoOJEbgQGIEDiRG4EBiBA4kRuBAYgQOJEbgQGKlAre90faHtk/YfqTuoQBUY87AbQ9J+q2kOyTdKGmr7RvrHgzA4MocwddIOhERJyPinKTnJW2qdywAVSgT+DJJpy76fKr4GoCOq+xNNts7bI/bHp+enq7qaQEMoEzgpyWtuOjz5cXXviIinoyIfkT0ly5dWtV8AAZQJvD3Jd1ge6XtqyRtkfRyvWMBqMKc/x48Is7bvl/S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yj4UNKIJNkeknRa0ks1zwWgAvM9Rb9N0j8j4l91DAOgWvMNfIuk5y71DbYuArqndODFpgd3S/r9pb7P1kVA98znCH6HpIMR8e+6hgFQrfkEvlX/5/QcQDeVCrzYD/x2SS/WOw6AKpXdm+xzSd+teRYAFeNKNiAxAgcSI3AgMQIHEiNwIDECBxIjcCAxAgcSc0RU/6T2tKT5/pPSJZLOVj5MN2R9bbyu9vwgIub8V121BH45bI9HRL/tOeqQ9bXxurqPU3QgMQIHEutS4E+2PUCNsr42XlfHdeZncADV69IRHEDFOhG47Y22P7R9wvYjbc9TBdsrbL9l+6jtI7YfbHumKtkesn3I9ittz1Il28O299k+bvuY7ZvbnmkQrZ+iF/da/4dm7xgzJel9SVsj4mirgw3I9rWSro2Ig7avkXRA0uaF/rousP0LSX1J34mIu9qepyq2n5H0p4jYVdxodFFEzLQ91+XqwhF8jaQTEXEyIs5Jel7SppZnGlhEfBQRB4uPP5V0TNKydqeqhu3lku6UtKvtWapke7GkWyQ9JUkRcW4hxy11I/Blkk5d9PmUkoRwge2epNWS3mt3ksrslPSwpC/bHqRiKyVNSxotfvzYVdyPcMHqQuCp2b5a0guSHoqIT9qeZ1C275J0JiIOtD1LDa6QdJOkJyJitaTPJS3o94S6EPhpSSsu+nx58bUFz/aVmo17T0RkuSPtWkl3257U7I9TG2w/2+5IlZmSNBURF8609mk2+AWrC4G/L+kG2yuLNzW2SHq55ZkGZtua/VnuWEQ83vY8VYmIRyNieUT0NPv/1ZsRcU/LY1UiIj6WdMr2quJLt0la0G+Klrptcp0i4rzt+yW9LmlI0tMRcaTlsaqwVtK9kv5ue6L42q8i4tUWZ8LcHpC0pzjYnJS0veV5BtL6r8kA1KcLp+gAakLgQGIEDiRG4EBiBA4kRuBAYgQOJEbgQGL/A9ozs2W/5x3pAAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x1088395c0>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "some_digit = X[666]\n",
    "some_digit_image = some_digit.reshape(8,8)\n",
    "plt.imshow(some_digit_image, cmap=matplotlib.cm.binary)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## train test split"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "from c1_knn.model_selection import train_test_split\n",
    "from c1_knn.kNN import KNNClassifier\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train, X_test, y_train, y_test = train_test_split(X, y, seed=666)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "my_knn_clf = KNNClassifier(k=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "kNN(k=3)"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_knn_clf.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.99164345403899723"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_predict = my_knn_clf.predict(X_test)\n",
    "# 正确率\n",
    "np.sum(y_predict==y_test) / np.shape(y_test)[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 把统计正确率封装为一个方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.99164345403899723"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from c1_knn.metrics import accuracy_score\n",
    "accuracy_score(y_test, y_predict)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## sklearn中的accuracy_score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection._split import train_test_split as train_test_spl\n",
    "from sklearn.neighbors.classification import KNeighborsClassifier\n",
    "from sklearn.metrics import accuracy_score as score\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train, X_test, y_train, y_test = train_test_spl(X, y, test_size=0.2, random_state=666)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',\n           metric_params=None, n_jobs=1, n_neighbors=3, p=2,\n           weights='uniform')"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "knn_clf = KNeighborsClassifier(n_neighbors=3)\n",
    "knn_clf.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "y_predict = knn_clf.predict(X_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.98888888888888893"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "score(y_test,y_predict)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.98888888888888893"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "knn_clf.score(X_test, y_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "两个score的结果一样"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
